package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"github.com/blevesearch/bleve"
	"log"
	"os"
	"strings"
)

func main() {
	//test()

	search("lbs_21q1v1_detail_scenic", "蜡像馆")

	//indexName := "example.bleve"
	//
	//createIndex(indexName)
	//
	//indexData(indexName)
	//
	//search(indexName, "example0")
}

func createIndex(indexName string) {
	mapping := bleve.NewIndexMapping()
	_, err := bleve.New(indexName, mapping)
	if err != nil {
		fmt.Println(err)
		return
	}
}

func indexData(indexName string) {
	message := struct {
		Id   string
		From string
		Body string
	}{
		Id:   "example0",
		From: "marty.schoch@gmail.com0",
		Body: "番茄炒鸡蛋gmail",
	}

	index, _ := bleve.Open(indexName)
	err := index.Index(message.Id, message)
	if err != nil {
		return
	}
	index.Close()
}

func test() {
	file, err := os.Open("E:\\A_SW\\topic-daily-equal-data.txt")
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	count := 0

	indexScenic, _ := bleve.Open("lbs_21q1v1_detail_scenic")
	indexGas, _ := bleve.Open("lbs_21q1v1_detail_gasstation")
	indexCater, _ := bleve.Open("lbs_21q1v1_detail_cater")

	//createIndex(indexName)

	for scanner.Scan() {

		lineText := scanner.Text()
		dataItem := strings.Split(lineText, "(|)")

		switch dataItem[0] {
		case "SCENIC":
			err := indexScenic.Index(dataItem[2], dataItem[4])
			if err != nil {
				return
			}
		case "GAS":
			err := indexGas.Index(dataItem[2], dataItem[4])
			if err != nil {
				return
			}
		case "CATER":
			err := indexCater.Index(dataItem[2], dataItem[4])
			if err != nil {
				return
			}
		default:
			fmt.Printf(dataItem[0])
			continue
		}

		count++
		fmt.Println(count)

	}

	indexScenic.Close()
	indexGas.Close()
	indexCater.Close()
}

func search(indexName, keyword string) {
	index, _ := bleve.Open(indexName)
	query := bleve.NewQueryStringQuery(keyword)
	searchRequest := bleve.NewSearchRequestOptions(query, 15, 0, false)
	searchRequest.Size = 20
	searchRequest.Fields = []string{"cityname"}
	searchResult, _ := index.Search(searchRequest)

	if searchResult.Total > 0 {
		doc, err := index.Document(searchResult.Hits[0].ID)
		if err != nil {
			fmt.Println(err)
		}

		data, _ := json.Marshal(doc)
		fmt.Println(string(data))

		j, _ := json.Marshal(*searchResult)

		fmt.Println(string(j))
	}
}
